package org.ruixue.service;

import org.apache.commons.lang3.StringUtils;
import org.ruixue.dao.oms.EcItemSkuMapper;
import org.ruixue.dao.oms.EcOrderMapper;
import org.ruixue.dao.oms.EcTradeMapper;
import org.ruixue.dao.oms.ShopMapper;
import org.ruixue.dao.yshop.StoreCartMapper;
import org.ruixue.dao.yshop.StoreOrderCartInfoMapper;
import org.ruixue.dao.yshop.StoreOrderMapper;
import org.ruixue.dao.yshop.UserAddressMapper;
import org.ruixue.entity.oms.EcItemSku;
import org.ruixue.entity.oms.EcOrder;
import org.ruixue.entity.oms.EcTrade;
import org.ruixue.entity.oms.Shop;
import org.ruixue.entity.yshop.StoreCart;
import org.ruixue.entity.yshop.StoreCartExample;
import org.ruixue.entity.yshop.StoreOrder;
import org.ruixue.entity.yshop.StoreOrderCartInfo;
import org.ruixue.entity.yshop.StoreOrderCartInfoExample;
import org.ruixue.entity.yshop.StoreOrderExample;
import org.ruixue.entity.yshop.UserAddress;
import org.ruixue.entity.yshop.UserAddressExample;
import org.ruixue.response.BaseResponse;
import org.ruixue.util.ByteUtil;
import org.ruixue.util.DateUtil;
import org.ruixue.util.SnoGerUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Service("orderService")
public class OrderService {

	/**
	 * OMS：网店表
	 */
	@Autowired
	private ShopMapper shopMapper;

	/**
	 * OMS：平台交易表
	 */
	@Autowired
	private EcTradeMapper ecTradeMapper;

	/**
	 * OMS:平台订单表
	 */
	@Autowired
	private EcOrderMapper ecOrderMapper;

	/**
	 * OMS：平台商品SUK表
	 */
	@Autowired
	private EcItemSkuMapper ecItemSkuMapper;

	/**
	 * 平台商城：订单表
	 */
	@Autowired
	private StoreOrderMapper storeOrderMapper;

	/**
	 * 平台商城：订单购物详情表
	 */
	@Autowired
	private StoreOrderCartInfoMapper storeOrderCartInfoMapper;

	/**
	 * 平台商城：用户地址表
	 */
	@Autowired
	private UserAddressMapper userAddressMapper;

	/**
	 * 平台商城：购物车表
	 */
	@Autowired
	private StoreCartMapper storeCartMapper;

	/**
	 * 获取全部订单（一个月内的订单）
	 *
	 * @return
	 * @throws Exception
	 */
	public BaseResponse downloadYiOrderWhole() throws Exception {
		// 获取当前时间戳
		Integer startTime = DateUtil.getTimeInMillis(-1);
		Integer endTime = DateUtil.getTimeInMillis(null);

		// 查询平台商城订单表数据
		StoreOrderExample soExample = new StoreOrderExample();
		soExample.createCriteria().andAddTimeBetween(startTime, endTime); // 创建时间
		List<StoreOrder> storeOrderList = storeOrderMapper.selectByExample(soExample);
		if (storeOrderList != null && storeOrderList.size() == 0) {
			return new BaseResponse("true", "获取订单数量为0");
		}

		// 获取订单ID
		List<Integer> oidList = new ArrayList<Integer>();
		oidList = storeOrderList.stream().map(StoreOrder::getId).collect(Collectors.toList());
		List<StoreOrderCartInfo> storeOrderCartInfoList = new ArrayList<StoreOrderCartInfo>();
		if (oidList.size() > 0) {
			// 查询平台商城订单购物详情表
			StoreOrderCartInfoExample sociExample = new StoreOrderCartInfoExample();
			sociExample.createCriteria().andOidIn(oidList);
			storeOrderCartInfoList = storeOrderCartInfoMapper.selectByExample(sociExample);
		}

		// 获取订单用户ID集合
		List<Integer> uidList = new ArrayList<Integer>();
		uidList = storeOrderList.stream().map(StoreOrder::getUid).collect(Collectors.toList());
		List<UserAddress> userAddressList = new ArrayList<UserAddress>();
		if (uidList.size() > 0) {
			// 查询用户详细地址表
			UserAddressExample uaExample = new UserAddressExample();
			uaExample.createCriteria().andUidIn(uidList).andIsDelEqualTo((byte) 0);
			userAddressList = userAddressMapper.selectByExample(uaExample);
		}

		// 获取订单用户ID集合
		List<StoreCart> storeCartList = new ArrayList<StoreCart>();
		if (storeOrderCartInfoList.size() > 0) {
			List<Integer> cartIdIntList = storeOrderCartInfoList.stream().map(StoreOrderCartInfo::getCartId)
					.collect(Collectors.toList());
			if (cartIdIntList.size() > 0) {
				List<Long> cartIdLongList = cartIdIntList.stream().map(a -> a.longValue()).collect(Collectors.toList());
				if (cartIdLongList.size() > 0) {
					// 查询购物车信息
					StoreCartExample scExample = new StoreCartExample();
					scExample.createCriteria().andIdIn(cartIdLongList);
					storeCartList = storeCartMapper.selectByExample(scExample);
				}
			}
		}

		// 保存数据
		return this.saveEcOrderMain(null, storeOrderList, storeOrderCartInfoList, userAddressList, storeCartList);
	}

	/**
	 * 获取订单（三个月内的订单）
	 *
	 * @param shopId
	 * @return
	 * @throws Exception
	 */
	public BaseResponse downloadYiOrder(String shopId) throws Exception {
		if (StringUtils.isBlank(shopId)) {
			return new BaseResponse("false", "shopId is null");
		}
		Shop shop = shopMapper.selectByPrimaryKeyShop(shopId);
		if (shop == null) {
			return new BaseResponse("false", "shop is null");
		}

		// 获取当前时间戳
		Integer startTime = DateUtil.getTimeInMillis(-2);
		Integer endTime = DateUtil.getTimeInMillis(null);

		// 查询平台商城订单表数据
		StoreOrderExample soExample = new StoreOrderExample();
		soExample.createCriteria().andMerIdEqualTo(Integer.parseInt(shop.getAppKey())) // 商户ID
				.andAddTimeBetween(startTime, endTime); // 创建时间
		List<StoreOrder> storeOrderList = storeOrderMapper.selectByExample(soExample);
		if (storeOrderList != null && storeOrderList.size() == 0) {
			return new BaseResponse("true", "获取订单数量为0");
		}

		// 获取订单ID
		List<Integer> oidList = new ArrayList<Integer>();
		oidList = storeOrderList.stream().map(StoreOrder::getId).collect(Collectors.toList());
		List<StoreOrderCartInfo> storeOrderCartInfoList = new ArrayList<StoreOrderCartInfo>();
		if (oidList.size() > 0) {
			// 查询平台商城订单购物详情表
			StoreOrderCartInfoExample sociExample = new StoreOrderCartInfoExample();
			sociExample.createCriteria().andOidIn(oidList);
			storeOrderCartInfoList = storeOrderCartInfoMapper.selectByExample(sociExample);
		}

		// 获取订单用户ID集合
		List<Integer> uidList = new ArrayList<Integer>();
		uidList = storeOrderList.stream().map(StoreOrder::getUid).collect(Collectors.toList());
		List<UserAddress> userAddressList = new ArrayList<UserAddress>();
		if (uidList.size() > 0) {
			// 查询用户详细地址表
			UserAddressExample uaExample = new UserAddressExample();
			uaExample.createCriteria().andUidIn(uidList).andIsDelEqualTo((byte) 0);
			userAddressList = userAddressMapper.selectByExample(uaExample);
		}

		// 获取订单用户ID集合
		List<StoreCart> storeCartList = new ArrayList<StoreCart>();
		if (storeOrderCartInfoList.size() > 0) {
			List<Integer> cartIdIntList = storeOrderCartInfoList.stream().map(StoreOrderCartInfo::getCartId)
					.collect(Collectors.toList());
			if (cartIdIntList.size() > 0) {
				List<Long> cartIdLongList = cartIdIntList.stream().map(a -> a.longValue()).collect(Collectors.toList());
				if (cartIdLongList.size() > 0) {
					// 查询购物车信息
					StoreCartExample scExample = new StoreCartExample();
					scExample.createCriteria().andIdIn(cartIdLongList);
					storeCartList = storeCartMapper.selectByExample(scExample);
				}
			}
		}

		// 保存数据
		return this.saveEcOrderMain(shop, storeOrderList, storeOrderCartInfoList, userAddressList, storeCartList);
	}

	/**
	 * 订单下载(按订单号)
	 *
	 * @param shopId
	 * @param ecTradeCode
	 * @return
	 * @throws Exception
	 */
	public BaseResponse downloadYiOrderByEcTradeCode(String shopId, String ecTradeCode) throws Exception {
		if (StringUtils.isBlank(shopId)) {
			return new BaseResponse("false", "shopId is null");
		}
		Shop shop = shopMapper.selectByPrimaryKeyShop(shopId);
		if (shop == null) {
			return new BaseResponse("false", "shop is null");
		}

		// 查询平台商城订单表数据
		StoreOrderExample soExample = new StoreOrderExample();
		soExample.createCriteria().andMerIdEqualTo(Integer.parseInt(shop.getAppKey())) // 商户ID
				.andOrderIdEqualTo(ecTradeCode); // 订单ID
		List<StoreOrder> storeOrderList = storeOrderMapper.selectByExample(soExample);
		if (storeOrderList != null && storeOrderList.size() == 0) {
			return new BaseResponse("true", "获取订单数量为0");
		}

		// 获取订单ID
		List<Integer> oidList = new ArrayList<Integer>();
		oidList = storeOrderList.stream().map(StoreOrder::getId).collect(Collectors.toList());
		List<StoreOrderCartInfo> storeOrderCartInfoList = new ArrayList<StoreOrderCartInfo>();
		if (oidList.size() > 0) {
			// 查询平台商城订单购物详情表
			StoreOrderCartInfoExample sociExample = new StoreOrderCartInfoExample();
			sociExample.createCriteria().andOidIn(oidList);
			storeOrderCartInfoList = storeOrderCartInfoMapper.selectByExample(sociExample);
		}

		// 获取订单用户ID集合
		List<Integer> uidList = new ArrayList<Integer>();
		uidList = storeOrderList.stream().map(StoreOrder::getUid).collect(Collectors.toList());
		List<UserAddress> userAddressList = new ArrayList<UserAddress>();
		if (uidList.size() > 0) {
			// 查询用户详细地址表
			UserAddressExample uaExample = new UserAddressExample();
			uaExample.createCriteria().andUidIn(uidList).andIsDelEqualTo((byte) 0);
			userAddressList = userAddressMapper.selectByExample(uaExample);
		}

		// 获取订单用户ID集合
		List<StoreCart> storeCartList = new ArrayList<StoreCart>();
		if (storeOrderCartInfoList.size() > 0) {
			List<Integer> cartIdIntList = storeOrderCartInfoList.stream().map(StoreOrderCartInfo::getCartId)
					.collect(Collectors.toList());
			if (cartIdIntList.size() > 0) {
				List<Long> cartIdLongList = cartIdIntList.stream().map(a -> a.longValue()).collect(Collectors.toList());
				if (cartIdLongList.size() > 0) {
					// 查询购物车信息
					StoreCartExample scExample = new StoreCartExample();
					scExample.createCriteria().andIdIn(cartIdLongList);
					storeCartList = storeCartMapper.selectByExample(scExample);
				}
			}
		}

		// 保存数据
		return this.saveEcOrderMain(shop, storeOrderList, storeOrderCartInfoList, userAddressList, storeCartList);
	}

	/**
	 * 订单接口以及中间表数据保存
	 * 
	 * @param shop
	 * @param storeOrderList
	 *            订单信息
	 * @param storeOrderCartInfoList
	 *            订单明细信息
	 * @param userAddressList
	 *            用戶地址信息
	 * @param storeCartList
	 *            购物车信息
	 * @return
	 * @throws Exception
	 */
	private BaseResponse saveEcOrderMain(Shop shop, List<StoreOrder> storeOrderList,
			List<StoreOrderCartInfo> storeOrderCartInfoList, List<UserAddress> userAddressList,
			List<StoreCart> storeCartList) throws Exception {
		// 循环订单数据
		for (int i = 0; i < storeOrderList.size(); i++) {
			StoreOrder storeOrder = storeOrderList.get(i);
			// 验证网店是否存在
			if (shop == null) {
				shop = shopMapper.selectByPrimaryKeyShop(storeOrder.getMerId().toString());
				if (shop == null) {
					return new BaseResponse("false", "shop is null");
				}
			}
			
			// 用于存储订单ID和商品ID，防止数据重复
			HashMap<String, String> oidMap=new HashMap<>();

			// 获取订单明细集合
			List<StoreOrderCartInfo> sociList = storeOrderCartInfoList.stream()
					.filter(s -> storeOrder.getId().equals(s.getOid())).collect(Collectors.toList());
			// 获取用户地址集合
			List<UserAddress> uaList = userAddressList.stream().filter(s -> s.getUid().equals(storeOrder.getUid()))
					.collect(Collectors.toList());
			// EcTrade 赋值
			EcTrade ecTrade = this.setEcTradeValue(shop, storeOrder, uaList);
			ecTrade.setDeleted("n");
			// 查询数据是否存在 - 平台表
			EcTrade ecTradeModel = ecTradeMapper.selectByPrimaryKeyEcTrade(ecTrade);
			if (ecTradeModel == null) {
				// 订单进EC中间表 oms_ec_trade.................
				// 插入
				ecTrade.setEcTradeId(SnoGerUtil.getUUID());
				ecTrade.setCreateTime(new Date());
				ecTradeMapper.insertSelectiveEcTrade(ecTrade);

				// 循环订单明细
				for (int j = 0; j < sociList.size(); j++) {
					StoreOrderCartInfo storeOrderCartInfo = sociList.get(j);
					// 订单实例化
					EcOrder ecOrder = new EcOrder();
					ecOrder.setEcTradeId(ecTrade.getEcTradeId());
					ecOrder.setShopId(ecTrade.getShopId());
					ecOrder.setEcTradeCode(ecTrade.getEcTradeCode());
					ecOrder.setEcOid(ecTrade.getEcTradeCode() + "_" + storeOrderCartInfo.getProductId());
					ecOrder.setEcItemCode(storeOrderCartInfo.getProductId().toString());
					ecOrder.setEcSkuCode(storeOrderCartInfo.getProductId().toString());

					// 判断如果重复跳出循环
					if(oidMap.get(ecOrder.getEcOid())!=null) {
						continue;
					}else {
						oidMap.put(ecOrder.getEcOid(), ecOrder.getEcOid());
					}
					
					// 获取平台商品上的商品名称和规格名称
					EcItemSku ecItemSku = new EcItemSku();
					ecItemSku.setShopId(ecTrade.getShopId());
					ecItemSku.setEcItemCode(storeOrderCartInfo.getProductId().toString());
					ecItemSku.setEcSkuCode(storeOrderCartInfo.getProductId().toString());
					EcItemSku ecItemSkuModel = ecItemSkuMapper.selectEcItemSkuBySkuId(ecItemSku);
					if (ecItemSkuModel != null) {
						ecOrder.setEcItemName(ecItemSkuModel.getGoodsName());
						ecOrder.setEcSkuName(ecItemSkuModel.getEcSkuName());
						// 标准单价
						ecOrder.setStanUnitPrice(ecItemSkuModel.getSalePrice());
						// 实际单价
						ecOrder.setFactUnitPrice(ecItemSkuModel.getSalePrice());
					} else {
						List<EcItemSku> ecItemSkuList = ecItemSkuMapper
								.selectEcItemSkuByEcItemCode(ecItemSku.getEcItemCode());
						if (ecItemSkuList.size() > 0) {
							ecItemSkuModel = ecItemSkuList.get(0);
							ecOrder.setEcItemName(ecItemSkuModel.getGoodsName());
							ecOrder.setEcSkuName(ecItemSkuModel.getEcSkuName());
							// 标准单价
							ecOrder.setStanUnitPrice(ecItemSkuModel.getSalePrice());
							// 实际单价
							ecOrder.setFactUnitPrice(ecItemSkuModel.getSalePrice());
						}
					}

					// 根据购物车获取订单明细商品数量
					List<StoreCart> scList = storeCartList.stream()
							.filter(s -> s.getId().intValue() == storeOrderCartInfo.getCartId().intValue()
									&& s.getProductId().equals(storeOrderCartInfo.getProductId()))
							.collect(Collectors.toList());
					if (scList.size() > 0) {
						// 数量
						ecOrder.setQty(scList.get(0).getCartNum().intValue());
					}
					// 使用积分
					if (storeOrder.getUseIntegral() != null) {
						ecOrder.setScore(storeOrder.getUseIntegral().intValue());
					}
					// 折扣
					BigDecimal bdDiscountFee = BigDecimal.ZERO;
					if (ecTrade.getTicketMoney() != null) {
						bdDiscountFee = bdDiscountFee.add(ecTrade.getTicketMoney());
					}
					ecOrder.setDiscountFee(bdDiscountFee);
					// 运费
					ecOrder.setLgstFee(ecTrade.getLgstFee());
					// 实际支付金额
					ecOrder.setDivideOrderFee(ecTrade.getPaidFee());
					// 平台订单状态
					ecOrder.setEcOrderStatus(ecTrade.getEcTradeStatus());
					// 物流公司
					if (StringUtils.isNotEmpty(storeOrder.getDeliverySn())) {
						ecOrder.setLgstName(storeOrder.getDeliverySn());
					}
					// 物流单号
					ecOrder.setLgstNo(storeOrder.getDeliveryId());
					// 插入
					ecOrder.setEcOrderId(SnoGerUtil.getUUID());
					ecOrder.setCreateTime(new Date());
					ecOrder.setDeleted(ecTrade.getDeleted());
					ecOrderMapper.insertSelectiveEcOrder(ecOrder);
				}
			} else {
				// 更新
				//ecTrade.setEcTradeId(ecTradeModel.getEcTradeId());
				ecTrade.setUpdateTime(new Date());
				ecTradeMapper.updateByPrimaryKeySelectiveEcTrade(ecTrade);
			}
		}
		return new BaseResponse();
	}

	/**
	 * EcTrade赋值
	 * 
	 * @param shop
	 * @param storeOrder
	 * @param sociList
	 * @param uaList
	 * @return
	 * @throws Exception
	 */
	private EcTrade setEcTradeValue(Shop shop, StoreOrder storeOrder, List<UserAddress> uaList) throws Exception {
		EcTrade ecTrade = new EcTrade();
		ecTrade.setEcTradeCode(storeOrder.getOrderId());
		ecTrade.setPrjId(shop.getPrjId());
		ecTrade.setPrjName(shop.getPrjName());
		ecTrade.setShopId(shop.getShopId());
		ecTrade.setShopName(shop.getShopName());
		ecTrade.setShopAccount(shop.getShopAccount());
		ecTrade.setShopType(shop.getShopType());
		ecTrade.setEcTradeStatus(this.getEcTradeStatusBystatus(storeOrder.getStatus()));
		ecTrade.setTradeType("一口价");
		ecTrade.setEcCustCode(storeOrder.getUid() + "");
		ecTrade.setEcCustName(storeOrder.getRealName());
		ecTrade.setCons(storeOrder.getRealName());
		ecTrade.setConsTel(storeOrder.getUserPhone());
		ecTrade.setConsMobile(storeOrder.getUserPhone());
		ecTrade.setConsAddr(storeOrder.getUserAddress());
		// 订单金额
		ecTrade.setTradeMoney(storeOrder.getTotalPrice());
		// 支付金额
		ecTrade.setPaidFee(storeOrder.getPayPrice());
		// 运费
		ecTrade.setLgstFee(storeOrder.getPayPostage());
		// 订单折扣(优惠单金额)
		ecTrade.setTradeDisc(storeOrder.getDeductionPrice());
		// 优惠券金额
		ecTrade.setTicketMoney(storeOrder.getCouponPrice());
		// 付款时间
		if (storeOrder.getPayTime() != null) {
			ecTrade.setPaidTime(DateUtil.timeStamp2Date(storeOrder.getPayTime() + ""));
		}
		// 完成时间
		if (StringUtils.isNotBlank(ecTrade.getEcTradeStatus())
				&& "EC_TRADE_FINISHED".equals(ecTrade.getEcTradeStatus())) {
			ecTrade.setEndTime(new Date());
		}
		// 买家备注
		if (StringUtils.isNotEmpty(storeOrder.getMark())) {
			ecTrade.setCustRemark(storeOrder.getMark());
		}
		// 卖家备注
		ecTrade.setSalesRemark(storeOrder.getRemark());
		// 刪除
		if (ByteUtil.byteToInt(storeOrder.getIsDel()) == 0) {
			ecTrade.setDeleted("n");
		} else {
			ecTrade.setDeleted("y");
		}
		// 拍单时间
		ecTrade.setOrderTime(DateUtil.timeStamp2Date(storeOrder.getAddTime() + ""));
		if (uaList != null && uaList.size() > 0) {
			List<UserAddress> userAddressList = uaList.stream()
					.filter(s -> s.getUid().equals(storeOrder.getUid()) && s.getRealName().equals(storeOrder.getRealName()))
					.collect(Collectors.toList());
			if (userAddressList.size() > 0) {
				UserAddress userAddress = uaList.get(0);
				// 注意: 直辖市可能需要特殊处理
				// 区域码
				String province_temp = userAddress.getProvince().replace("市", "");
				if (province_temp.contains("广西")) {
					province_temp = "广西壮族自治区";
				} else if (province_temp.contains("西藏")) {
					province_temp = "西藏自治区";
				} else if (province_temp.contains("宁夏")) {
					province_temp = "宁夏回族自治区";
				} else if (province_temp.contains("新疆")) {
					province_temp = "新疆维吾尔自治区";
				} else if (province_temp.contains("内蒙古")) {
					province_temp = "内蒙古自治区";
				}
				String province = "";
				if (!province_temp.contains("省") && !"北京".equals(province_temp) && !"上海".equals(province_temp)
						&& !"天津".equals(province_temp) && !"重庆".equals(province_temp)
						&& !"广西壮族自治区".equals(province_temp) && !"西藏自治区".equals(province_temp)
						&& !"宁夏回族自治区".equals(province_temp) && !"新疆维吾尔自治区".equals(province_temp)
						&& !"内蒙古自治区".equals(province_temp)) {
					province = province_temp + "省";
				} else {
					province = province_temp;
				}
				// 省
				ecTrade.setProvName(province);
				// 市
				ecTrade.setCityName(userAddress.getCity());
				// 区
				ecTrade.setDistName(userAddress.getDistrict());
				// 邮编
				ecTrade.setConsPostCode(userAddress.getPostCode());
			}
		}
		// 付款方式
		ecTrade.setPayMethod(storeOrder.getPayType());
		return ecTrade;
	}

	/**
	 * 订单状态 0待发货、1已发货、2和3交易成功、-1 和-2交易关闭
	 * 
	 * @param status
	 * @return
	 */
	private String getEcTradeStatusBystatus(Byte statusByte) {
		String result = null;
		int status = ByteUtil.byteToInt(statusByte);
		switch (status) {
		case 0:
			result = "EC_WAIT_SELLER_SEND";
			break;
		case 1:
			result = "EC_TRADE_ALL_SEND";
			break;
		case 2:
			result = "EC_TRADE_FINISHED";
			break;
		case 3:
			result = "EC_TRADE_FINISHED";
			break;
		case -1:
			result = "EC_TRADE_CANCELED";
			break;
		case -2:
			result = "EC_TRADE_CANCELED";
			break;
		default:
			result = "EC_WAIT_BUYER_PAY";
			break;
		}
		return result;
	}
}
